# Greeting people (with functions)
# Much better!
def greet(your_name):
print(f"Nice to meet you, {your_name}!")
greet("Alice")
greet("Bob")
greet("Danilo")Nice to meet you, Alice!
Nice to meet you, Bob!
Nice to meet you, Danilo!
Because copy-pasting code is so last semester
Emory University
https://danilofreire.github.io/job-talk-emory/lecture.html
February 07, 2025
def)return# Greeting people (without functions)
# Don't do this at home!
print("Nice to meet you, Alice!")
print("Nice to meet you, Bob!")
print("Nice to meet you, Charlie!")
print("Nice to meet you, Danilo!")
print("Nice to meet you, Emily!")
print("Nice to meet you, Frank!")
print("Nice to meet you, George!")
# ... repeats 993 more times ...Maybe there’s a better way to do this? 🤔
print(), type(), np.mean(), plt.hist() are all functions you’ve used before! 🤓# Greeting people (with functions)
# Much better!
def greet(your_name):
print(f"Nice to meet you, {your_name}!")
greet("Alice")
greet("Bob")
greet("Danilo")Nice to meet you, Alice!
Nice to meet you, Bob!
Nice to meet you, Danilo!
DRY principle: Don’t Repeat Yourself 😉
def keyword. Tells Python: “We are defining a function now”function_name). Choose a descriptive name (e.g., greet, calculate_age, etc)(). Enclose inputs the function needs. Empty () means no inputsparameter). A placeholder for the values the function will receive. Can be multiple, separated by commasparameter=argument). The actual values that will be passed to the function.: Ends the function header. Don’t forget it!return statement (optional). What the function sends back. If absent, function returns None. Indent it too!say_greeting(name)return statement?message_alice = say_greeting("Alice")?say_greeting?greeting_type="Hello" part? What does it mean?message_bob = get_greeting("Bob") and then print(message)?We can use the result in further calculations!
More about the return statement here
calculate_area function below 👇length=5 and width=4, and print the resultname before greeting_typereturn statement)lambda arguments: expression
lambda x, y: x + ytravel_distance using the formula speed * timespeed = 100 and time = 2message from outside:message has disappeared!global keywordIf you want to change a global variable inside a function, you need to use the global keyword
This tells Python: “Hey, I’m talking about the global variable here!”
Let’s see an example:
global_greeting is not passed as an argument to the function?$, @, print, sum, list)def f(x):, def function1():, def sum():, def cR@zY_fUnC(): 👎def calculate_area():, def greet_user():, def download_wbi(): 👍docstrings to document your functions! 📚""" or ''')return, and more!IndentationError!
print instead of returnreturn a value when you need onedef keyword, name, parameters, body, return, and indentationglobal keyword to change global variables inside functionsreturn statementsprint instead of returnreturn inside loops or if statementsCourse website: https://danilofreire.github.io/qtm151/
Course website: https://danilofreire.github.io/qtm350/
Course website: https://danilofreire.github.io/qtm385/
transformers, trl, datasets), SMoLM2, and ollamadistilabel
for loopsfor loops inside functionsprint, len)*args: Packing Positional Arguments*args and **kwargs are great tools for writing flexible functions*args: Packing Positional Arguments*args has got you covered! It:
args*args = “arguments” (with a star to make it special!)def make_pizza(*toppings):
print("Making a pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza("pepperoni", "mushrooms")Making a pizza with the following toppings:
- pepperoni
- mushrooms
Making a pizza with the following toppings:
- cheese
- onions
- olives
- sausage
**kwargs: Packing Keyword Arguments**kwargs handles a variable number of keyword arguments!kwargsdef user_profile(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
user_profile(name="Alice", age=30, city="Wonderland")name: Alice
age: 30
city: Wonderland
occupation: Coder
hobby: Python
level: Beginner
kwargs is a dictionary! Access arguments by key*args must come before **kwargs in the function definitiontry and except blocks to catch and handle errorsdef get_list_item_safe(my_list, index):
"""
Safely gets an item from a list at a given index,
handling IndexError.
"""
try:
item = my_list[index]
return item
except IndexError:
return "Error: Index is out of range!"
my_list = ["apple", "banana", "cherry"]
print(get_list_item_safe(my_list, 1))
print(get_list_item_safe(my_list, 5)) banana
Error: Index is out of range!
except IndexError: catches errors when the index is invalid for the list!
Without try...except, your program would crash with an IndexError if you tried to access an invalid index.
Think of it as a safety net for your code!
This is especially useful when: